package Psh::Builtins::Dbcore;

require Psh::Completion;
require Psh::Sql;

=item * C<dbcore DB_command_line (many words)>

Parses tokens, and sends everything after the "dbcore" to the 
open database handle.  If you have any shell like tokens (> < |) in your 
line then they will be treated shell-like and not sent to the SQL handle.

If you just want the entire line sent identically to SQL, then use the
strategy "db SQL command" instead of "dbcore SQL command".

=cut

sub bi_dbcore
{
	my $line=shift;
	my @ARGV = @{shift()};

	# remove the first word, which is the command to be run
	$line =~ s/^\s*(\S+)\s*//;
	my $dbcom = $1;
	my $argv_dbcom = shift @ARGV;
		
	Psh::Util::print_debug("Running db command: $dbcom $line\n");

	if ($dbcom ne $argv_dbcom) {
		Psh::Util::print_debug("command line mismatch: dbcom=$dbcom argv1=$argv_dbcom\n");
		#return (0,undef);
	}

	if ($dbcom eq "head") {
		Psh::Sql::db_head($line, \@ARGV);
	} elsif ($dbcom eq "open") {
		Psh::Sql::db_open($line, \@ARGV);
	} elsif ($dbcom eq "ls") {
		Psh::Sql::db_ls($line, \@ARGV);
	} elsif ($dbcom eq "rehash") {
		Psh::Sql::db_rehash($line, \@ARGV);
	} elsif ($dbcom eq "use") {
		Psh::Sql::db_use($line, \@ARGV);
	} elsif ($dbcom eq "") {
		Psh::Util::print_out("currently connected to... " . 
		   join(":", $Psh::Sql::type , $Psh::Sql::curdb) . "\n");
	} else {
		Psh::Sql::db_run("$dbcom $line");
	}	

	return(1,undef);
}

sub cmpl_dbcore {
	my( $text, $dummy, $starttext, $whole_line) = @_;
	my $understand_input = 0;
	if ($dummy eq "") {
		# if dummy is blank, then that is the normal mode for builtins
		# and all variables are properly assigned
		$understand_input = 1;
	} elsif ($starttext =~ /^\d+$/) {
		# if dummy has a value, then this function must have been
		# added as a completion function via a "complete -F" command
		my $last_space = $starttext;
		$whole_line = $dummy;
		$starttext = substr($whole_line,0,$last_space);
		$dummy = "";
		$understand_input = 1;
	} 
	
	if (! $understand_input) {
		Psh::Util::print_error("[Cannot make completion list]");
		my (@args) = ($text, $dummy, $starttext, $whole_line);
		foreach my $i ( 0 .. $#args) {
			Psh::Util::print_debug("\n[$i = $args[$i]]\n");
		}
		return(0,undef);
	}

	return(Psh::Sql::cmpl_sql($text, $starttext));
	#my @words= split ' ',$starttext;
	#$Psh::Completion::ac=' ';
	# text has the current word, dummy seems blank and starttext has the beginning of the line
	#return (1,grep { Psh::Util::starts_with($_,$text) }
			#Psh::Sql::completions($text, $starttext) );

}

1;
